<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command\ocean;

use app\command\BaseWork;
use app\enum\ConfigEnum;
use app\enum\OceanEnum;
use app\service\batch\OceanBatchService;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Cache;

class ProductDelWork extends BaseWork
{
    protected function configure()
    {
        // 指令配置
        $this->setName('ocean_product_del_work');
        // 设置参数
        $this->setDescription('巨量2.0-删除产品');

        // 设置参数
        $this->setHelp('php think ocean_product_del_work');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->getOutputMessage('巨量2.0-删除产品开始');

        $redis = Cache::store('redis')->handler();
        $runTime = time() + 5 * 60;
        $redisKey = ConfigEnum::CACHE_CONFIG[OceanEnum::BATCH_CONFIG_KEY]['product_del'];
        while (time() < $runTime) {
            $idStr = $redis->lpop($redisKey);
            if (! $idStr) {
                $this->getOutputMessage('暂无删除数据');
                sleep(rand(5, 10));
                continue;
            }

            $arr = explode('|||', $idStr);
            $advId = strval($arr[0]);
            $version = intval($arr[1]);

            $this->getOutputMessage('同步[adv_id:' . $advId . ']开始');

            try {
                $res = OceanBatchService::batchProductDel($advId, $version);
                if ($res === false) {
                    $this->getOutputMessage('无数据删除');
                }

                $this->getOutputMessage('同步[adv_id:' . $advId . ']成功');
            } catch (\Exception $e) {
                $this->getOutputMessage($e->getMessage());
                $this->getOutputMessage($e->getFile() . '[' . $e->getLine() . ']');
                $this->getOutputMessage($e->getTraceAsString());
            }

            $this->getOutputMessage('同步[adv_id:' . $advId . ']结束');
        }

        $this->getOutputMessage('巨量2.0-删除产品结束');
    }
}
